<?php
namespace App\Admin\Models;
use Common\BaseModel;
class Member extends BaseModel
{
    protected $res;
    protected $redis_key = "admin_";

    public function getSource()
    {
        return "f_users";
    }


    /**
     * @func 根据手机号获取用户的信息
     */
    public function find_by_phone($phone)
    {
        $user_info = $this->findFirstByPhone($phone);
        if (!$user_info) {
            return false;
        } else {
            return $user_info->toarray();
        }
    }


    /**
     * func 根据微信删除openid获取用户的信息
     * @return bool
     */
    public function find_by_wxaccountobj($phone)
    {
        $user_info = $this->findFirstByWxAccount($phone);
        return $user_info;
    }


    /**
     * @param string $keywords 关键字
     * @param int $page_size 长度
     * @param int $page
     * @param string $flag
     * @return mixed
     */
    public function member_list($params, $page_size = 10, $page = 1, $flag = '')
    {
        $conditions = '1=1 ';
        if ($params['keywords']) {
            $conditions .= " and (phone like '%{$params['keywords']}%' or nickname like '%{$params['keywords']}%')";
        }
        if ($params['is_appuser'] != '') {
            if ($conditions) {
                $conditions .= " AND is_appuser={$params['is_appuser']}";
            }
        }


        if (isset($params['level_id']) && !empty($params['level_id'])) {
            if ($params['level_id'] != 5) {
                if ($conditions) {
                    $conditions .= " AND level_id={$params['level_id']}";
                }
            } else {
                $WWW                    = new WwwExtend();
                $wwwWhere['conditions'] = "svip_forever = 1";
                $wwwWhere['columns']    = "user_id";
                $ids                    = $WWW->find($wwwWhere)->toarray();
                if (!empty($ids)) {
                    $idStr      = implode(',', array_column($ids, 'user_id'));
                    $conditions .= " AND id in ($idStr)";
                }
            }
        }


        if (isset($params['created_at']) && !empty($params['created_at'])) {
            if ($conditions) {
                $conditions .= " AND (created_at >='{$params['created_at'][0]}' and created_at <= '{$params['created_at'][1]}')";
            } else {
                $conditions = "(created_at >='{$params['created_at'][0]}' and created_at <= '{$params['created_at'][1]}')";
            }
        }

        if (isset($params['user_id']) && !empty($params['user_id'])) {
            $conditions .= " AND id = {$params['user_id']}";
        }

        $user_list['total'] = 0;
        $order              = 'id desc';
        if (isset($params['order']) && !empty($params['order'])) {
            switch ($params['order']) {
                case 1:
                    $object = new Orders();
                    break;
                case 2:
                    $object = new Wallets();
                    break;
                case 3:
                    $object = new UserMonthIncome();
                    break;
            }
            $objectList = $object->get_count_list($params);
            if (!empty($objectList['list'])) {
                $uid        = implode(',', array_column($objectList['list'], 'user_id'));
                $conditions .= " AND id in ({$uid})";
                $order      = 'field(id,' . $uid . ')';

            }
            $user_list['total'] = $objectList['count'];
        }
        $offset = ($page - 1) * $page_size;
        if ($user_list['total'] == 0) {
            $sql = "select * from Member where {$conditions} order by $order limit {$offset},{$page_size}";
        } else {
            $sql = "select * from Member where {$conditions} order by $order limit {$offset},{$page_size}";
        }

        $user_list['items'] = $this->modelsManager->executeQuery($sql)->toarray();

//        $user_list['items'] = $this::find(
//            array(
//                $conditions,
//                "limit"  => $page_size,
//                "offset" => ($page - 1) * $page_size,
//                'order'  => ''
//            ))->toarray();

        if ($user_list['total'] == 0) {
            $user_list['total'] = $this::count(
                array(
                    $conditions,
                    "columns" => 'id',
                ));
        }
        return $user_list;
    }

    public function member_list_two($params, $page_size = 10, $page = 1, $flag = '')
    {
        $conditions = '1=1 ';
        if ($params['keywords']) {
            $conditions .= " and (a.phone like '%{$params['keywords']}%' or a.nickname like '%{$params['keywords']}%' or a.invite_code = '{$params['keywords']}')";
        }
        if ($params['is_appuser'] != '') {
            if ($params['is_appuser'] <= 1) {
                $conditions .= " AND a.is_appuser={$params['is_appuser']}";
            }
            if ($params['is_appuser'] == 3) {
                $conditions .= " AND a.is_disable=1";
            }
            if ($params['is_appuser'] == 4) {
                $conditions .= " AND a.is_buyed=1";
            }
            if ($params['is_appuser'] == 5) {
                $conditions .= " AND a.is_buyed=0";
            }
        }

        if(isset($params['is_buyed']) && !empty($params['is_buyed'])){
            $conditions .= " AND a.is_buyed=1";
        }


        if (isset($params['level_id']) && !empty($params['level_id'])) {
            $conditions .= " AND a.level_id={$params['level_id']}";
        }

        if (isset($params['created_at']) && !empty($params['created_at'])) {
            $conditions .= " AND a.created_at >='{$params['created_at'][0]}' and a.created_at <= '{$params['created_at'][1]}'";
        }

        if (isset($params['user_id']) && !empty($params['user_id'])) {
            $conditions .= " AND a.id = {$params['user_id']}";
        }

        $user_list['total'] = 0;


        $order = 'id desc';
        if (isset($params['order']) && !empty($params['order'])) {
            $order = $params['order'];
        }

        $offset = ($page - 1) * $page_size;

        $sql             = "select a.remark,a.is_buyed,a.is_disable,a.invite_code,a.path,a.created_at,a.id,a.is_appuser,a.avatar,a.nickname,a.phone,a.level_id,a.referer_id,order_count,c.amount,d.withdraws,e.commissions from f_users as a 
left join (select count(user_id) as order_count,user_id from `w_union_order` group by user_id) as b on b.user_id = a.id
left join f_wallets as c on c.user_id = a.id
left join (select sum(money) as withdraws,user_id from `f_withdrawals` where status in (1,2,8) group by user_id) as d on d.user_id = a.id 
left join (select sum(money) as commissions,user_id from `w_order_commissions` where order_status in (2,4,6) group by user_id) as e on e.user_id = a.id 
where $conditions order by $order limit {$offset},{$page_size}";
        $list            = $this->getDI()->get('dbMaster')->fetchAll($sql);
        $result['items'] = $list;
        $sql             = "select count(*) as `count` from f_users as a 
left join (select count(user_id) as order_count,user_id from `w_union_order` group by user_id) as b on b.user_id = a.id
left join f_wallets as c on c.user_id = a.id
left join (select sum(money) as withdraws,user_id from `f_withdrawals` where status in (1,2,8) group by user_id) as d on d.user_id = a.id where $conditions";
        $total           = $this->getDI()->get('dbMaster')->fetchOne($sql);
        $result['total'] = $total['count'] ? $total['count'] : 0;
        return $result;
    }

    /**
     * @param 通过path找到所有的上级,拼接电话好嘛
     * @path 全路径，已经加上了直推人的id
     */
    public function get_referer_list($path)
    {
        $ids = substr($path, 2);
        if (empty($ids)) {
            $ids = '-1';
        }
        $conditions = "id in({$ids})";
        $str_phone  = '';
        $user_list  = $this::find(
            array(
                $conditions,
                "columns" => 'id,phone',
            ))->toarray();
        foreach ($user_list as $key => $value) {
            $str_phone .= $value['phone'] . ' ';
        }
        return $str_phone;
    }


    /**
     * 根据id获取用户信息
     */
    public function find_first_by_Id($id)
    {
        if (empty($id)) {
            return '';
        }
        $user_info = $this->findFirstById($id);
        if ($user_info) {
            $user_info = $user_info->toarray();
            return $user_info['phone'];
        } else {
            return [];
        }
    }


    /**
     * 根据id获取用户信息
     */
    public function find_by_id($id)
    {
        if (empty($id)) {
            return '';
        }
        $user_info = $this->findFirstById($id);
        if ($user_info) {
            return $user_info->toarray();
        } else {
            return [];
        }

    }


    /**
     * 获取系统总人数
     */
    public function countNumber($data = [])
    {
        $conditions = '';
        if ((isset($data['start_at']) && !empty($data['start_at']))) {
            $conditions = "created_at >= '{$data['start_at']}' AND created_at <= '{$data['end_at']}'";
        }
        if ((isset($data['is_appuser']) && $data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser=1";
            } else {
                $conditions = "is_appuser = 1";
            }
        }
        $user_count = $this::count(
            array(
                $conditions,
                "columns" => 'id',
            ));
        return $user_count;
    }


    /**
     * 测试方法，每次修改一千条
     */
    public function update_raw()
    {
        $conditions = 'is_count=0';
        $user_count = $this::find(
            array(
                $conditions,
                "limit" => 1000
            ));
        return $user_count->toarray();
    }


    /**
     * @func 根据邀请码获取用户
     */
    public function find_by_inviteCode($invite_code)
    {
        $conditions['conditions'] = "invite_code = '{$invite_code}' or  phone = '{$invite_code}' or exclusive_code='{$invite_code}'";
        $user_info                = $this->findFirst($conditions);
        if (!$user_info) {
            return false;
        } else {
            $info = $user_info->toarray();
            if ($info['nickname'] || $info['wx_nickname'] || $info['phone']) {
                $info['nickname'] = $info['nickname'] ? $info['nickname'] : $info['wx_nickname'];
                if (empty($info['nickname'])) {
                    $phone            = substr_replace($info['phone'], '****', 3, 4);
                    $info['nickname'] = $phone;
                }
            } else {
                $info['nickname'] = '没有填写';
            }
            return $info;
        }
    }


    /**
     * @func 更新/插入数据
     * @param $data要更新或者要插入的数据
     * @return boolean 插入成功的结果
     */
    public function save_user($data)
    {
        $data['updated_at'] = date('Y-m-d H:i:s', time());
        $result             = $this->save($data);
        return $result;
    }

    /**
     *   10月17日0:00点之前的联创，
     *   20个注册登录巨折的保级联创，
     *   10-19个的降级总监，
     *   10个以下降级会员
     * 测试方法，每次修改一千条
     */
    public function level_update_raw()
    {
        $conditions = "created_at <= '2019-10-17 00:00:00' AND level_id=3 AND level_count=0";
        $user_count = $this::find(
            array(
                $conditions,
                "limit" => 2000
            ));
        return $user_count->toarray();
    }


    /**
     * 10月17日0:00点之后的联创，
     * 50个注册登录巨折的保级联创
     * 10-19个的降级总监，
     * 10个以下降级会员
     * 测试方法，每次修改一千条
     */
    public function level_update_after_raw()
    {
        $conditions = "created_at > '2019-10-17 00:00:00' AND level_id=3 AND level_count=0";
        $user_count = $this::find(
            array(
                $conditions,
                "limit" => 2000
            ));
        return $user_count->toarray();
    }


    /**
     * 10月17日0:00点之后的联创，
     * 50个注册登录巨折的保级联创
     * 10-19个的降级总监，
     * 10个以下降级会员
     * 测试方法，每次修改一千条
     */
    public function update_zongjian_level()
    {
        $conditions = "level_id=2 and level_count=0";
        $user_count = $this::find(
            array(
                $conditions,
                "limit" => 2000
            ));
        return $user_count->toarray();
    }

    /**
     * 25日23:59总监考核
     * 不满10人活粉，降级会员
     * 满10-19人活粉，保级总监
     * 满20人活粉，升级联创
     */
    public function update_zongjian_level_two()
    {
        $conditions = "created_at <= '2019-10-25 23:59:59' AND level_id=2 AND level_count=1";
        $user_count = $this::find(
            array(
                $conditions,
                "limit" => 2000
            ));
        return $user_count->toarray();
    }


    /**
     * @param $user_id 获取我的直推人数
     * @return mixed
     */
    public function direct_vip($user_id)
    {
        $condition        = "referer_id={$user_id} AND is_appuser=1 AND is_disable=0";
        $direct_vip_count = $this::count(
            array(
                $condition,
                "limit"   => 1,
                "cloumns" => 'id'
            )
        );
        return $direct_vip_count;
    }


    /**
     * 查询直接邀请粉丝数量（直邀）
     */
    public function getDirectFansCount($user_id, $data)
    {
        if ($data['start_end_time']) {
            $conditions = "referer_id = {$user_id} AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
        } else {
            $conditions = "referer_id = {$user_id}";
        }
        if (isset($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions = "is_appuser={$data['is_appuser']}";
            }
        }
        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= " AND is_buyed={$data['is_buyed']}";
            } else {
                $conditions .= " is_buyed={$data['is_buyed']}";
            }
        }
        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
        ));
        return $count_array;
    }


    /**
     * @func 根据微信的openid获取用户的信息
     */
    public function find_by_wxaccount($phone)
    {
        $user_info = $this->findFirstByWxAccount($phone);
        if (!$user_info) {
            return false;
        } else {
            return $user_info->toarray();
        }
    }


    /**
     * 获取我的间推人数
     */
    public function indirect_vip($path)
    {
        $condition        = "path like '{$path}%' AND is_appuser=1 AND is_disable=0";
        $direct_vip_count = $this::count(
            array(
                $condition,
                "limit"   => 1,
                "cloumns" => 'id'
            )
        );
        return $direct_vip_count;
    }

    public function save_member($params)
    {
        return $this::save($params);
    }


    public function userCompare($today, $lastday)
    {
        $condition = "created_at >= '{$today['start_at']}' and created_at <= '{$today['end_at']}'";
        $todayInfo = $this::count(
            $condition
        );
        $condition = "created_at >= '{$lastday['start_at']}' and created_at <= '{$lastday['end_at']}'";
        $lastInfo  = $this::count(
            $condition
        );
        return $todayInfo - $lastInfo;
    }

    public function subordinate_count($uid)
    {
        $where['conditions'] = "referer_id = $uid";
        $where['columns']    = 'count(id) as count';
        $count               = $this->findFirst($where);
        return $count->count ? $count->count : 0;
    }

    public function team_num($uid, $referer_id, $path = '')
    {
        $where    = "referer_id = $uid";
        $refCount = $this->count($where);
        if ($path) {
            $jianpath = $path . ',' . $referer_id . ',' . $uid;
        } else {
            $jianpath = $referer_id . ',' . $uid;
        }
        $where     = "path = '$jianpath'";
        $jianCount = $this->count($where);
        $where     = "path like '$jianpath%' and path != '$jianpath'";
        $teamCount = $this->count($where);

        return [
            'direct'   => $refCount,
            'indirect' => $jianCount,
            'team'     => $teamCount,
            'count'    => $refCount + $teamCount + $jianCount
        ];
    }


    //根据日期查找
    public function datetime_day($datetime)
    {
        $datetime['start_at'] = $datetime['start_at'] . ' 00:00:00';
        $datetime['end_at']   = $datetime['end_at'] . ' 23:59:59';
        $phql                 = "SELECT DATE_FORMAT( created_at, '%Y-%m-%d' ) AS datetime,count(id) as datacount FROM f_users  where created_at>='{$datetime['start_at']}' and created_at<='{$datetime['end_at']}' GROUP BY DATE_FORMAT( created_at, '%Y-%m-%d' )";
        $items                = $this->getDI()->get('dbMaster')->fetchAll($phql);
        $new_date             = [];
        foreach ($items as $key => $value) {
            $new_date[$value['datetime']] = $value['datacount'];
        }
        return $new_date;
    }


    public function count_member($datetime)
    {
        $conditions = "created_at>='{$datetime['start_at']}' and created_at<='{$datetime['end_at']}'";
        $count      = $this->count(array(
            $conditions,
        ));
        return $count;
    }



    public function count_member_all()
    {
        $count      = $this->count();
        return $count;
    }

}
